//
//  UserSingleton.m
//  Router
//
//  Created by teki on 15/10/22.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "UserSingleton.h"

#define FILE_NAME (@"userdata.data")

@implementation UserSingleton
+ (instancetype) shareInstance
{
    static UserSingleton *_obj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _obj = [[UserSingleton alloc] init];
        NSString *filePath = [_obj filePath];
        _obj.userModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        if (_obj.userModel)
        {
            UserModel *model = [_obj.userModel.user objectAtIndex:0];
            if (model && model.userName)
            {
                _obj.password =  [[NSUserDefaults standardUserDefaults] objectForKey:model.userName];
            }
        }
    });
    return _obj;
}


- (void)setPassword:(NSString *)password
{
    _password = password;
    UserModel *user = self.userModel.user[0];
    if (user && user.userName) {
        [[NSUserDefaults standardUserDefaults] setObject:password forKey:user.userName];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

}




- (BOOL)saveData
{
    NSString *filePath = [self filePath];
    BOOL isSuccess = [NSKeyedArchiver archiveRootObject:self.userModel toFile:filePath];
    if (isSuccess)
    {
        NSLog(@"数据保存成功!");
    }
    else{
        NSLog(@"数据保存失败!");
    }

    return isSuccess;
}



#pragma mark -
#pragma mark   PrivateMethods
- (NSString *)filePath
{
    NSString *DocumentsPath = [self getDocumentsPath];
    NSString *filePath = [DocumentsPath stringByAppendingPathComponent:FILE_NAME];
    return filePath;
}


- (NSString *)getDocumentsPath{
    //获取Documents路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"Documents path:%@", path);
    return path;
}
@end
